import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/pages/basic/company/widget/item.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class BasicCompanyPage extends StatefulWidget {
  const BasicCompanyPage({super.key});

  @override
  State<BasicCompanyPage> createState() => _BasicCompanyPageState();
}

class _BasicCompanyPageState extends State<BasicCompanyPage> {
  List<dynamic> list = [{}, {}, {}, {}, {}, {}, {}];
  ListPaginationModel pagination = ListPaginationModel();
  RefreshController refreshController = RefreshController();
  String keyword = '';
  bool isReady = false;
  @override
  void initState() {
    super.initState();
  }

  fetchData() async {
    var res = await Http.instance.post(
      '/api/basic/company/index',
      data: {
        "page": pagination.currentPage,
        "keyword": keyword,
      },
    );

    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  String get placeholder {
    var user = AuthService.instance.user;
    if (user.isSubstation == false && user.substationId! > 0) {
      return '在${user.substationName}中搜索';
    }
    return '请输入关键词';
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      dismissOnCapturedTaps: true,
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: UiTheme.of(context).match(light: Colors.white),
          scrolledUnderElevation: 0,
          title: const Text('供热企业'),
          actions: const [
            UiRightMenuButtonGroup(),
          ],
        ),
        body: UiLifeCycle(
          onRouteDone: fetchData,
          child: Column(
            children: [
              Container(
                color: UiTheme.of(context).match(
                  light: Colors.white,
                  dark: Theme.of(context).appBarTheme.backgroundColor,
                ),
                padding: const EdgeInsets.only(
                  top: UiTheme.toolbarSpacing,
                  left: UiTheme.spacingX,
                  right: UiTheme.spacingX,
                  bottom: UiTheme.spacingX,
                ),
                alignment: Alignment.centerLeft,
                child: UiSearchBar(
                  placeholder: placeholder,
                  backgroundColor:
                      UiTheme.of(context).match(light: Colors.grey[100]),
                  onSubmitted: (val) {
                    keyword = val;
                    pagination.currentPage = 1;
                    fetchData();
                  },
                  onClear: () {
                    keyword = '';
                    pagination.currentPage = 1;
                    fetchData();
                  },
                ),
              ),
              const Divider(height: 0),
              Expanded(
                child: UiPushToRefresh(
                  controller: refreshController,
                  onRefresh: () {
                    pagination.currentPage = 1;
                    fetchData();
                  },
                  enablePullUp:
                      pagination.lastPage > 1 && !refreshController.isRefresh,
                  onLoad: () {
                    pagination.currentPage++;
                    fetchData();
                  },
                  child: list.isEmpty
                      ? const Center(
                          child: UiResult(),
                        )
                      : ListView.separated(
                          separatorBuilder: (context, index) => const SizedBox(
                            height: UiTheme.spacingX,
                          ),
                          itemBuilder: (context, index) {
                            var item = list[index];
                            return BasicCompanyItemView(
                              item: item,
                              index: index,
                            );
                          },
                          itemCount: list.length,
                        ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
